package com.roc.web.action.agent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.AgentSubsidyBean;
import com.roc.bean.ChangeAgentCountBean;
import com.roc.bean.ChangeCheckCountBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.count.ChangeCheckCountSearchCondition;
/**
 * 代理商补贴
 * @ClassName AgentSubsidyAction
 * @Description: TODO(...)
 * @author JD
 * @date 2017年7月12日下午4:44:36
 *
 */
@Action
@Component
@Scope("prototype")
@Namespace("/agentSubsidy")
public class AgentSubsidyAction   extends PaginationBaseAction{
	
	/**
	 * file
	 * long:serialVersionUID:AgentSubsidyAction.java
	 */
	
	private static final long serialVersionUID = 1L;
	private Logger logger=LogManager.getLogger(AgentSubsidyAction.class);
	private AgentSubsidySearchCondition searchCondition;
	
	private ByteArrayInputStream excelFile;
	@Autowired
	private IExcelService excelService;

	@Autowired
	IPageService pagenitionService;
	
	@Autowired
	private IPageService  pageService;
	
	/**
	 * 代理商补助主页面
	 * @Title: init
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年7月12日 下午4:48:05
	 *
	 */
	@Action(value="init",results={ @Result(name="success",location="/pages/agent/queryAgentSubsidy.jsp")})
	public String init(){
			return SUCCESS;
	}
	/**
	 *代理商补助查询
	 * @Title: queryAgentSubsidy
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年7月12日 下午4:49:53
	 *
	 */
	@Action(value="queryAgentSubsidy",results={@Result(name="success",location="/pages/agent/queryAgentSubsidy.jsp")})
	public String  queryAgentSubsidy(){
		logger.info("开始进行代理商补贴查询");
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			if(searchCondition==null){
				searchCondition=(AgentSubsidySearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new AgentSubsidySearchCondition();
				}
			}
			searchCondition.setRoleType(op.getRoleType());
			//特约商户
			if(Role.MERCHANT.getCode().equals(op.getRoleType())){
				searchCondition.setMerNo(op.getAccountNo());
			}//代理商
			else if(Role.AGENT.getCode().equals(op.getRoleType())){
				String agentId= String.valueOf(op.getId());
				searchCondition.setAgentId(agentId);
				
			}else if(Role.AGENT_BUSS.getCode().equals(op.getRoleType())){
				 searchCondition.setOpId(String.valueOf(op.getId()));
			}else{
				searchCondition.setOrgCode(op.getOrgCode());
			}
			int rows=pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<AgentSubsidyBean> agent =  new ArrayList<AgentSubsidyBean>();
			if (searchRsList != null && searchRsList.size() > 0) {
				Iterator iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					AgentSubsidyBean age = new AgentSubsidyBean();
					age.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
					age.setNameBusi(Constance.Null2EmptyTrim(obj[1]));
					age.setCertif(Constance.Null2EmptyTrim(obj[2]));
					age.setCertifNo(Constance.Null2EmptyTrim(obj[3]));
					age.setBusiLiceNo(Constance.Null2EmptyTrim(obj[4]));
					age.setAgentName(Constance.Null2EmptyTrim(obj[5]));
					age.setOneAgentName(Constance.Null2EmptyTrim(obj[6]));
					age.setCompanyName(Constance.Null2EmptyTrim(obj[7]));
					age.setMerchantBankAccount(Constance.Null2EmptyTrim(obj[8]));
					age.setMerchantBankAccountName(Constance.Null2EmptyTrim(obj[9]));
					age.setMerchantBankName(Constance.Null2EmptyTrim(obj[10]));
					age.setDeviceCd(Constance.Null2EmptyTrim(obj[11]));
					age.setAllAmt(Constance.Null2EmptyTrim(obj[12]));
					age.setAllCount(Constance.Null2EmptyTrim(obj[13]));
					age.setTransMonth(Constance.Null2EmptyTrim(obj[14]));
					age.setMerinfoStatus(Constance.Null2EmptyTrim(obj[15]));
					age.setTerminalStatus(Constance.Null2EmptyTrim(obj[16]));
					
					agent.add(age);
				}
					getRequest().setAttribute("agent", agent);
					this.setTotalPage(this.calcuTotalPage(rows));
					getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
					getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
					getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
					setSearchToConditionSession(searchCondition);
					addActionMessage("当前条件下统计到【" + rows + "】条记录");
				    }
				} catch (ServiceException e) {
					e.printStackTrace();
					logger.error(e.getMessage(), e);
					addActionError(e.getMessage()); 
				}
					
		return SUCCESS;
		
	}
	/**
	 * 代理商补贴查询---导出
	 * @Title: exportAgentSubsidy
	 * @Description:TODO(...)
	 * @see <p></p>
	 * @return
	 * @author JD
	 * @date: 2017年7月20日 下午2:44:38
	 *
	 */
	@Action(value = "exportAgentSubsidy", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/pages/agent/queryAgentSubsidy.jsp") })
   public String exportAgentSubsidy(){
         logger.info("导出代理商补贴excel开始");
         Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
         try {
		if(searchCondition==null){
			searchCondition=(AgentSubsidySearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new AgentSubsidySearchCondition();
			}
		}
		searchCondition.setRoleType(op.getRoleType());
		//特约商户
		if(Role.MERCHANT.getCode().equals(op.getRoleType())){
			searchCondition.setMerNo(op.getAccountNo());
		}//代理商
		else if(Role.AGENT.getCode().equals(op.getRoleType())){
			String agentId= String.valueOf(op.getId());
			searchCondition.setAgentId(agentId);
			
		}else if(Role.AGENT_BUSS.getCode().equals(op.getRoleType())){
			 searchCondition.setOpId(String.valueOf(op.getId()));
		}else{
			searchCondition.setOrgCode(op.getOrgCode());
		}
			
			
			int rows=pagenitionService.countSQL(searchCondition);
			
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<AgentSubsidyBean> agentList = new ArrayList<AgentSubsidyBean>();
			dealWith(agentList,searchRsList);
			logger.info("rows:" + rows + "    searchRsList.size():"+ agentList.size());
			HSSFWorkbook work = excelService.exportAgentSubsidyList(agentList);

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();

			logger.info("导出代理商补贴excel结束");
		} catch (Exception e) {
			logger.info("导出代理商补贴数据异常："+e);
		}
		
	    return SUCCESS;
   }

	
	private List<AgentSubsidyBean> dealWith(List<AgentSubsidyBean> agentList,List<Object> searchRsList) {
		if(searchRsList!=null&&searchRsList.size()>0)
		{
			Iterator<?> iterator=searchRsList.iterator();
			while(iterator.hasNext())
			{
				Object[] obj=(Object[]) iterator.next();
				AgentSubsidyBean age = new AgentSubsidyBean();
				age.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				age.setNameBusi(Constance.Null2EmptyTrim(obj[1]));
				age.setCertif(Constance.Null2EmptyTrim(obj[2]));
				age.setCertifNo(Constance.Null2EmptyTrim(obj[3]));
				age.setBusiLiceNo(Constance.Null2EmptyTrim(obj[4]));
				age.setAgentName(Constance.Null2EmptyTrim(obj[5]));
				age.setOneAgentName(Constance.Null2EmptyTrim(obj[6]));
				age.setCompanyName(Constance.Null2EmptyTrim(obj[7]));
				age.setMerchantBankAccount(Constance.Null2EmptyTrim(obj[8]));
				age.setMerchantBankAccountName(Constance.Null2EmptyTrim(obj[9]));
				age.setMerchantBankName(Constance.Null2EmptyTrim(obj[10]));
				age.setDeviceCd(Constance.Null2EmptyTrim(obj[11]));
				age.setAllAmt(Constance.Null2EmptyTrim(obj[12]));
				age.setAllCount(Constance.Null2EmptyTrim(obj[13]));
				age.setTransMonth(Constance.Null2EmptyTrim(obj[14]));
				age.setMerinfoStatus(Constance.Null2EmptyTrim(obj[15]));
				age.setTerminalStatus(Constance.Null2EmptyTrim(obj[16]));
				agentList.add(age);
			}
		}
		return agentList;
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		 return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_BEAN_AGENT_SUBSIDY,searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (AgentSubsidySearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_AGENT_SUBSIDY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}
	public AgentSubsidySearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(AgentSubsidySearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public ByteArrayInputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(ByteArrayInputStream excelFile) {
		this.excelFile = excelFile;
	}
	public String getExcelName() {
		String excelName = "代理商补贴" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			// e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;

 }
}